package testclient1;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Timer;
import java.util.TimerTask;


public class ChannelClient {
	private final String HOST = "223.93.67.122";
	private final int PORT = 11805;
	//注释详见com.telesound.nio.server.ClientThread.java
	private SocketChannel socketChannel;
	private Selector selector = null;
	private InputStream in;
	private OutputStream out;
	
	public ChannelClient() throws IOException {
		// TODO Auto-generated constructor stub
		initialize();//初始化
		comhandNet();
	}

	public static void main(String[] args) throws IOException {
		ChannelClient c = new ChannelClient();
		byte[] bytes = new byte[]{0x5B, 0x00, 0x00, 0x00, 0x43, 0x00, 0x00, 0x00, (byte) 0x8C, 0x20, 0x01, 0x00, (byte) 0x98, (byte) 0x96,
				(byte) 0x85, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, (byte) 0x88, 0x59, 0x00, (byte) 0x98, (byte) 0x96, (byte) 0x85, 0x20, 0x21,
				0x04, 0x27, 0x10, 0x37, 0x54, 0x38, 0x39, 0x62, 0x30, 0x33, 0x30, 0x38, 0x32, 0x65, 0x36, 0x31, 0x31, 0x30, 0x38, 0x63, 0x61,
				0x64, 0x31, 0x37, 0x65, 0x31, 0x33, 0x36, 0x64, 0x32, 0x63, 0x66, 0x36, 0x63, 0x62, 0x31, 0x65, (byte) 0xD3, (byte) 0xD8, 0x5D};
		c.sendData(bytes);
	}

	private void comhandNet() {
		Timer timer = new Timer();
		timer.schedule(new TimerTask() {
			@Override
			public void run() {
				byte[] heartBeat = new byte[]{
						0x5B,
						0x00 ,0x00 ,0x00 ,0x17,
						0x00 ,0x00 ,0x00 , (byte) 0x8C,
						0x20 ,0x05,
						0x00 , (byte) 0x98, (byte) 0x96, (byte) 0x85,
						0x01 ,0x00 ,0x00,
						0x00,
						0x00 ,0x00 , (byte) 0x88,0x59,
						(byte) 0xD3, (byte) 0xD8,
						0x5D
				};
				try {
					sendData(heartBeat);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}, 0, 10000);
	}

	//初始化客户端连接
	private void initialize() throws IOException {
		// TODO Auto-generated method stub
		//打开监听通道
		socketChannel  = SocketChannel.open(new InetSocketAddress(HOST,PORT));
		//设置非阻塞模式
		socketChannel.configureBlocking(false);

		//打开选择器并注册到信道
		selector = Selector.open();
		socketChannel.register(selector,SelectionKey.OP_READ|SelectionKey.OP_WRITE);//读取集
		//启动读取的线程----
		new ChannelReadClient(selector);
	}

	/**
	 * 发送数据到服务器
	 * @param byout
	 * @throws IOException
	 */
	public void sendData(byte[] byout) throws IOException{
		ByteBuffer writeBuf = ByteBuffer.wrap(byout,0,byout.length);
		socketChannel.write(writeBuf);
//		out = socketChannel.socket().getOutputStream();
//		out.write(byout);
	}
}
